package edu.hawaii.duedates;

import com.meterware.httpunit.GetMethodWebRequest;
import com.meterware.httpunit.HttpUnitOptions;
import com.meterware.httpunit.WebConversation;
import com.meterware.httpunit.WebForm;
//import com.meterware.httpunit.WebLink;
import com.meterware.httpunit.WebRequest;
import com.meterware.httpunit.WebResponse;
import com.meterware.httpunit.WebTable;

/**
 * Due Date Bootstrap demonstrates simple use of httpunit to retrieve and parse a web page. 
 * 
 * @author Philip Johnson
 */
public class DueDates {
  
  /**
   * Attempts to login to UH Manoa Library system.  
   * @param id The UH user ID. 
   * @param lastName  The UH user's last name. 
   * @return The WebConversation instance after successful login. 
   * @throws Exception If login was not successful with these credentials. 
   */
  WebConversation loginToUhLibrary(String id, String lastName) throws Exception {
    String url = "http://uhmanoa.lib.hawaii.edu/cgi-bin/Pwebrecon.cgi?DB=local&PAGE=pbLogon";
    // UH Library website has bogus JavaScript code.
    HttpUnitOptions.setExceptionsThrownOnScriptError(false);
    // create the conversation object which will maintain state for us
    WebConversation conversation = new WebConversation();
    WebRequest request = new GetMethodWebRequest(url);
    WebResponse response = conversation.getResponse(request);
    WebForm form = response.getFormWithName("logonpage");
    form.setParameter("BC", id);
    form.setParameter("LN", lastName);
    form.submit();
    response = conversation.getCurrentPage();
    if (response.getText().contains("Sorry, Login unsuccessful")) {
      throw new Exception("Error while logging in to UH Library");
    }
    return conversation;
  }
  
  /**
   * Attempts to login to the Hawaii State Library System.
   * @param id The hawaii library id barcode.
   * @param password The password (last four digits of your phone number).
   * @return The WebConversation after logging in. 
   * @throws Exception If errors occur while logging in. 
   */
  /**private WebConversation loginToHawaiiStateLibrary(String id, String password) throws 
   * Exception {
    try {
    String url = "http://www.librarieshawaii.org/";
    // Website has bogus JavaScript code.
    HttpUnitOptions.setExceptionsThrownOnScriptError(false);
    // create the conversation object which will maintain state for us
    WebConversation conversation = new WebConversation();
    WebRequest request = new GetMethodWebRequest(url);
    WebResponse response = conversation.getResponse(request);
    WebLink link = response.getLinkWith("My Account");
    link.click();
    response = conversation.getCurrentPage();
    WebForm form = response.getForms()[0];
    form.setParameter("sec1", "0011429495");
    form.setParameter("sec2", "3845");
    form.submit();
    return conversation;
    }
    catch (Exception e) {
      throw new Exception ("Error while logging in to Hawaii State Library", e);
    }
  }
  */
  
  /**
   * Given a logged in user to the UH Library site, provides info about their library books. 
   * @param id The UH user ID. 
   * @param lastName  The UH user's last name.    
   * @return A String containing information about their books.
   * @throws Exception If problems occur parsing the site pages. 
   */
  public String getUhInfo(String id, String lastName) throws Exception {
    String uhSiteNoItemString = "You have no items checked out.";
    try {
      WebConversation conversation = this.loginToUhLibrary(id, lastName);
      WebResponse response = conversation.getCurrentPage();
      WebForm form = response.getForms()[0];
      if (uhSiteNoItemString.equals(form.getText())) {
        return "No items checked out";
      }
      else {
        // Assume the first table is the one we need. Not true in general.
        WebTable table = response.getTables()[0];
        String format = "%1$-15s  %2$-70s\n";
        String bookInfo = "";
        bookInfo = bookInfo.concat(String.format(format, "Due Dates", "Book Information" ));
        for (int i = 1; i < table.getRowCount(); i++) {
          bookInfo = bookInfo.concat(String.format(format,table.getCellAsText(i, 3).substring(13),
              table.getCellAsText(i, 1).substring(0,70) + " ..."));
        }
        return bookInfo;
      }
    }
    catch (Exception e) {
      throw new Exception("Error getting UH Book info", e);
    }
  }
  
  /**
   * Gets info from the Hawaii State Library site.
   * @param hiStateId The barcode number from the library card.
   * @param hiStatePassword The password (normally the last four digits of your phone number).
   * @return A string providing information about checked out books. 
   * @throws Exception If problems occur getting the information. 
   */
  /**public String getHawaiiStateInfo(String hiStateId, String hiStatePassword) throws Exception {
    try {
      WebConversation conversation = this.loginToHawaiiStateLibrary(hiStateId, hiStatePassword);
      WebResponse response = conversation.getCurrentPage();
      WebLink link = response.getLinkWith("Items Out");
      link.click();
      response = conversation.getCurrentPage();
      boolean noBooksOut = response.getText().contains("Checked Out: 0");
      return (noBooksOut) ? "No items checked out" : "At least one item checked out.";
    }
    catch (Exception e) {
      throw new Exception("Error getting Hawaii State Library info", e);
    }
  }
 */
  /**
   * The main class illustrates the use of this code to login in systems. 
   * 
   * @param params Four strings: uhID, uhLastName, hiStateId, hiStatePassword.
   * @throws Exception If problems occur accessing the library sites. 
   */
  public static void main(String[] params) throws Exception {
    DueDates dueDate = new DueDates();
    // Check UH Manoa Library
    String library = params[0];
    if ("-uhm".equals(library)) {
      String uhId = params[1];
      String uhLastName = params[2];
      if (uhId.length() == 8) {
        System.out.printf("Getting data from UH Manoa%n");
        String uhInfo = dueDate.getUhInfo(uhId, uhLastName);
        System.out.printf("Results for UH Manoa:%n%s%n", uhInfo);  
      }
      else {
        System.out.printf("Please input correct student number!");
      }
    }
    else if ("-hsl".equals(library)) {
      System.out.printf("Sorry, Hawaii State Library information is not available " +
        "with this version");
    }
    else {
      System.out.println("Please input correct library code.");
    }
    /**
    // Check the Hawaii State Library.
    String hiStateId = params[3];
    String hiStatePassword = params[4];
    System.out.printf("Getting data from Hawaii State Library System (this can take 1 minute)%n");
    String hiInfo = dueDate.getHawaiiStateInfo(hiStateId, hiStatePassword);
    System.out.printf("Results for Hawaii State Library:%n %s%n", hiInfo);
    */
  }
}

